﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Single.Cache
{
    public static class CacheHelper
    {
        private static IMemoryCache cache = new MemoryCache(Options.Create(new MemoryCacheOptions()));

        public static T? GetOrCreate<T>(string key, int minutes, Func<T> func)
        {
            Func<ICacheEntry, T> gocFunc = (entry) =>
            {
                entry.SetSlidingExpiration(TimeSpan.FromMinutes(minutes));
                return func.Invoke();
            };

            return cache.GetOrCreate(key, gocFunc);
        }

        public static void Remove(string key)
        {
            object? value;

            if (cache.TryGetValue(key, out value)) { cache.Remove(key); }
        }
    }
}